/**
 * Created by gaoyj on 2018/6/28.
 */
window.onload = function (ev) {
    topbar.hide();
};

function mergeCellsByField(tableID, colList) {
    var ColArray = colList.split(",");
    var tTable = $('#' + tableID);
    var TableRowCnts = tTable.bootstrapTable("getData").length;
    var tmpA;
    var tmpB;
    var PerTxt = "";
    var CurTxt = "";
    var alertStr = "";
    //for (j=0;j<=ColArray.length-1 ;j++ )
    for (j = ColArray.length - 1; j >= 0; j--) {
        //当循环至某新的列时，变量复位。
        PerTxt = "";
        tmpA = 1;
        tmpB = 0;

        //从第一行（表头为第0行）开始循环，循环至行尾(溢出一位)
        for (i = 0; i <= TableRowCnts; i++) {
            if (i == TableRowCnts) {
                CurTxt = "";
            }
            else {
                CurTxt = tTable.bootstrapTable("getData")[i][ColArray[j]];
            }
            if (PerTxt == CurTxt) {
                tmpA += 1;
            }
            else {
                tmpB += tmpA;
                tTable.bootstrapTable('mergeCells', {
                    index: i - tmpA,
                    field: ColArray[j],
                    rowspan: tmpA,
                    colspan: null
                });
                tmpA = 1;
            }
            PerTxt = CurTxt;
        }
    }
}

$('#dataTable').bootstrapTable({
    url: '/CollectCardStockReportController/collectCardStockReportPage',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    showFooter: true,
    responseHandler: function (res) {
        return {
            "total": res.total,
            "rows": res.resultList
        };
    },
    columns: [[
        {
            width: '3px',
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        }, {
            field: 'cardOperatorName', title: '运营商', width: 90, align: 'center', formatter: function (v, o) {
                return v;
            },
            footerFormatter: function (value) {
                return "合计";
            }
        },
        {
            field: 'totalStockAmount', title: '库存', width: 90, align: 'center', formatter: function (v, r) {
            return v;
        }, footerFormatter: function (value) {
            var count = 0;
            for (var i in value) {
                count = parseFloat(count) + parseFloat(value[i].totalStockAmount);
            }
            return count.toFixed(4) + "";
        }
        },
        {
            field: 'face', title: '销卡面值', width: 90, align: 'center', footerFormatter: function (value) {
            var count = 0;
            for (var i in value) {
                count = parseFloat(count) + parseFloat(value[i].face);
            }
            return count.toFixed(4) + "";
        }
        },
        {
            field: 'totalUploadFace', title: '金额', width: 70, align: 'center', footerFormatter: function (value) {
            var count = 0;
            for (var i in value) {
                count = parseFloat(count) + parseFloat(value[i].totalUploadFace);
            }
            return count.toFixed(4) + "";
        }
        },
        {
            field: 'showPrice', title: '价格', width: 70, align: 'center', formatter: function (v, o) {
            if (v == 0 || o.productType == 999) {
                return v;
            }
            var s = JSON.stringify(o);
            return "<a href='javascript:void(0)' onclick='showPrice(" + s + ")'>显示</a>"
        }
        },
        {
            field: 'showTime', title: '时间', width: 70, align: 'center', formatter: function (v, o) {
            if (v == 0 || o.productType == 999) {
                return v;
            }
            var s = JSON.stringify(o);
            return "<a href='javascript:void(0)' onclick='showTime(" + s + ")'>显示</a>"
        }
        },
        {field: 'sumTotal', title: '总面值', width: 70, align: 'center'}
    ]],
    onLoadSuccess: function (data) {
        var totalData = {};
        data = $('#dataTable').bootstrapTable("getData");
        for (var i = 0; i < data.length; i++) {
            var row = data[i];
            if (totalData[row.productType + "SUM"] == undefined) {
                totalData[row.productType + "SUM"] = 0;
            }
            totalData[row.productType + "SUM"] += row.totalUploadFace;
        }
        for (var i = 0; i < data.length; i++) {
            data[i].sumTotal = totalData[data[i].productType + "SUM"];
            $("#dataTable").bootstrapTable("updateRow", {
                index: i,
                row: data[i]
            });
        }
        mergeCellsByField("dataTable", "sumTotal");
    }
});

$("#search").click(function () {
    var timeAdd = new Date($("#startTime").val());
    var timeEnd = new Date($("#endTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    $("#dataTable").bootstrapTable("refresh");
});

function showPrice(data) {
    $("#typeDetailtable").bootstrapTable('destroy');
    $("#typeDetailtable").bootstrapTable({
        url: "/CollectCardStockReportController/collectCardStockPricePage",
        height: $(window).height() - 330,
        pageSize: 1000,
        pagination: true,
        pageList: [1000, 2000, 3000],
        clickToSelect: true,
        queryParams: {size: 1000, page: 1, productType: data.productType, face: data.face},
        uniqueId: 'id',
        queryParamsType: '',
        sidePagination: 'server',
        showFooter: true,
        responseHandler: function (res) {
            return {
                "total": res.total,//总页数
                "rows": res.resultList   //数据
            };
        },
        columns: [[
            {
                field: 'area', title: '销卡地区', align: 'center', width: 150, footerFormatter: function (v, o) {
                return "平均折扣";
            }
            },
            {field: 'userPrice', title: '提交折扣', align: 'center', width: 200, footerFormatter: avgDiscount},
            {field: 'totalStockAmount', title: '库存数量', width: 200, align: 'center', footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].totalStockAmount);
                }
                return count.toFixed(4) + "";
            }}
        ]]
    });
    var title = data.cardOperatorName + data.face + "元";
    $("#detailModalLabel").html(title);
    $("#detailModal").modal("show");
}

function avgDiscount(data) {
    var avg = 0;
    var sumDiscount = 0;
    var sumStockAmount = 0;
    for (var i = 0; i < data.length; i++) {
        sumDiscount = sumDiscount + data[i].userPrice * data[i].totalStockAmount;
        sumStockAmount = sumStockAmount + data[i].totalStockAmount;
    }
    avg = sumDiscount / sumStockAmount
    return (Math.round((avg) * 10000) / 10000).toFixed(4);
}

function showTime(data) {
    $("#typeDetailtable").bootstrapTable('destroy');
    $("#typeDetailtable").bootstrapTable({
        url: "/CollectCardStockReportController/apiEstimateStockSupplyTime",
        pageSize: 2,
        pagination: false,
        pageList: [2, 50, 100],
        clickToSelect: true,
        queryParams: {productType: data.productType, face: data.face, account: $("#account").val()},
        uniqueId: 'id',
        queryParamsType: '',
        sidePagination: 'server',
        responseHandler: function (res) {
            return {
                "rows": res
            };
        },
        columns: [[
            {field: 'area', title: '销卡地区', align: 'center', width: 80},
            {field: 'halfHour', title: '半小时用量', align: 'center', width: 80},
            {field: 'oneHour', title: "一小时用量", width: 80, align: 'center'},
            {field: 'twoHour', title: '两小时用量', width: 80, align: 'center'},
            {field: 'totalStockAmount', title: '库存数量', width: 80, align: 'center'},
            {
                field: 'availableTime',
                title: '可用时间(分钟)',
                width: 90,
                align: 'center',
                formatter: function (v, o) {
                    return calctime(o);
                }
            },
            {field: 'frontCount', title: '排队卡数量', width: 80, align: 'center'},
            {
                field: 'frontCount', title: '预计到达时间(分钟)', width: 80, align: 'center',
                formatter: function (v, o) {
                    return getCostTime(o);
                }
            }
        ]],
        onLoadSuccess: function (data) {
            $(".easyui-tooltip").tooltip({showDelay: 1, position: 'right'});
        }
    });
    var title = data.cardOperatorName + data.face + "元";
    $("#detailModalLabel").html(title);
    $("#detailModal").modal("show");
}

function calctime(s) {
    var half = s.halfHour;
    var one = s.oneHour;
    var two = s.twoHour;
    if (half && one && two && s.totalStockAmount) {
        var averageSpeed = Math.ceil((half * 0.7 / 30 + one * 0.2 / 60 + two * 0.1 / 120) / 3);
        return (s.totalStockAmount / averageSpeed).toFixed(0);
    }
    return "-";
}

function getCostTime(s) {
    var half = s.halfHour;
    if (half && s.frontCount) {
        return (s.frontCount / (half / 30)).toFixed(0);
    }
    return "-";
}
$(function () {
    $.ajax({
        type: "POST",
        url: "/CardProductController/queryAllCardOperatorList",
        dataType: "json",
        success: function (data) {
            $("#productType").html("");
            var str = "<option value=\"\">全部</option>";
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += '<option value=' + data[i].cardOperatorId + '>' + data[i].cardOperatorName + '</option>'
                }
            }
            $("#productType").append(str);
            //缺一不可  
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('render');
        },
        beforeSend: function () {
        }
    });
})
function queryParams(params) {
    return {
        size: params.pageSize,
        page: params.pageNumber,
        productType: $("#productType").val(),
        face: $("#face").val(),
    };
}